package com.qdlc.p2p.biz.service.impl;

import java.util.Arrays;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.Response;
import com.qd.p2p.adapter.enums.ResponseStatus;
import com.qd.p2p.adapter.param.FlowBorrowParam;
import com.qd.p2p.adapter.param.FullBorrowLoanParam;
import com.qd.p2p.adapter.param.RepayBorrowParam;
import com.qd.p2p.adapter.param.TenderBorrowParam;
import com.qd.p2p.adapter.param.TransferAccountsParameter;
import com.qd.p2p.adapter.response.FlowBorrowResponse;
import com.qd.p2p.adapter.response.FullBorrowLoanResponse;
import com.qd.p2p.adapter.response.GenericResponse;
import com.qd.p2p.adapter.response.RepayBorrowResponse;
import com.qd.p2p.adapter.response.TenderBorrowResponse;
import com.qd.p2p.adapter.response.TransferAccountsResponse;
import com.qd.p2p.baofoo.enums.AccountType;
import com.qd.p2p.baofoo.enums.FeeTakenOnType;
import com.qdlc.p2p.biz.service.RPCRequestService;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.DataUtils;
import com.qdlc.p2p.common.util.LogFactory;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.dao.BorrowDao;
import com.qdlc.p2p.dal.dao.BorrowTenderDao;
import com.qdlc.p2p.dal.dto.Borrow;
import com.qdlc.p2p.dal.dto.BorrowTender;
import com.qdlc.p2p.dal.dto.TppTradeLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.util.UserUtils;

@Service("bfRPCRequestService")
public class BFRPCRequestServiceImpl implements RPCRequestService<Response, TppTradeLog> {

    /**
     * 交易Log
     */
    private static final Logger logger = LogFactory.TRADE_LOGGER;

    @Resource
    private AdaptedRequestHandleService adaptedPayService;

    @Resource
    private BorrowDao borrowDao;

    @Resource
    private BorrowTenderDao borrowTenderDao;

    @Value("${bofoo.borrow.id.prx}")
    private String borrowPrx;

    @Override
    public Response tenderRequest(TppTradeLog tppTradeLog) {
        Response response = new TenderBorrowResponse();
        try {
            // 标信息
            Borrow borrow = borrowDao.find(tppTradeLog.getBorrowId());
            TenderBorrowParam parameter = new TenderBorrowParam();
            parameter.setOrderId(tppTradeLog.getOrderNo()); // 订单号
            parameter.setReqTime(tppTradeLog.getAddTime().getTime()); // 请求时间
            String testBorrowId = borrowPrx + String.valueOf(tppTradeLog.getBorrowId());
            parameter.setBorrowId(testBorrowId); // 标ID
            parameter.setBorrowName(borrow.getName()); // 标名字
            parameter.setBorrowUserId(String.valueOf(borrow.getUser().getTppUserCustId())); // 借款人用户ID
            parameter.setBorrowUserName(borrow.getUser().getUserName()); // 借款人用户名

            Map<String, Object> memo = DataUtils.getMemo(tppTradeLog.getMemo());
            String tenderUserId = (String) memo.get("tenderUserId"); // 投标用户标识
            String tenderUserName = (String) memo.get("tenderUserName"); // 投标用户标识

            // 投标用户
            TenderBorrowParam.TenderUser tenderUser = new TenderBorrowParam.TenderUser();
            tenderUser.setUserId(UserUtils.getUserTppCustId(Long.parseLong(tenderUserId)));
            tenderUser.setUserName(tenderUserName);
            tenderUser.setAmount(tppTradeLog.getMoney()); // 投标金额
            parameter.setTenderUser(tenderUser);
            response = adaptedPayService.tender(parameter);
        } catch (Exception e) {
            response.setResponseMsg("RPC 调用失败");
            response.setStatus(ResponseStatus.FAILURE);
            logger.info("BFRPCRequestServiceImpl#tenderRequest 调用失败 ", e);
        }
        return response;
    }

    @Override
    public Response repayRequest(TppTradeLog tppTradeLog) {
        Response response = new GenericResponse();
        response.setResponseMsg("提交成功");
        response.setStatus(ResponseStatus.SUCCESS);
        return response;
    }

    @Override
    public Response repayPayRequest(TppTradeLog tppTradeLog) {
        Response response = new RepayBorrowResponse();
        try {
            // 标信息
            Borrow borrow = borrowDao.find(tppTradeLog.getBorrowId());
            RepayBorrowParam parameter = new RepayBorrowParam();
            parameter.setOrderId(tppTradeLog.getOrderNo()); // 订单号
            parameter.setReqTime(tppTradeLog.getAddTime().getTime()); // 请求时间
            String testBorrowId = borrowPrx + String.valueOf(tppTradeLog.getBorrowId());
            parameter.setBorrowId(testBorrowId); // 标ID
            parameter.setBorrowName(borrow.getName()); // 标名字
            parameter.setBorrowUserId(String.valueOf(borrow.getUser().getTppUserCustId())); // 借款人用户ID
            parameter.setBorrowUserName(borrow.getUser().getUserName()); // 借款人用户名

            Map<String, Object> memo = DataUtils.getMemo(tppTradeLog.getMemo());
            String tenderUserId = (String) memo.get("tppUserId"); // 投标用户标识
            String tenderUserName = (String) memo.get("tppUserName"); // 投标用户

            // 平台收取投资人管理费
            double interestManage = 0.0d;
            String interestManageStr = StringUtil.isNull(memo.get("interestManage"));
            if (StringUtil.isNotBlank(interestManageStr)) {
                interestManage = BigDecimalUtil.round(DataUtils.toDouble(interestManageStr), 2);
            }

            // 投标用户
            RepayBorrowParam.TenderUser tenderUser = new RepayBorrowParam.TenderUser();
            tenderUser.setUserId(tenderUserId);
            tenderUser.setUserName(tenderUserName);
            tenderUser.setAmount(tppTradeLog.getMoney()); // 投标金额
            tenderUser.setFee(interestManage); // 平台收取投资人管理费
            parameter.setTenderUsers(Arrays.asList(tenderUser));
            parameter.setFee(0.0d); // 平台收取借款人手续费
            response = adaptedPayService.repay(parameter);
        } catch (Exception e) {
            response.setResponseMsg("RPC 调用失败");
            response.setStatus(ResponseStatus.FAILURE);
            logger.info("BFRPCRequestServiceImpl#repayRequest 调用失败 ", e);
        }
        return response;
    }

    @Override
    public Response repayUpRateRequest(TppTradeLog tppTradeLog) {
        return getSuccessResponse();
    }

    @Override
    public Response repayUpRatePayRequest(TppTradeLog tppTradeLog) {
        return transferFromPlatform(tppTradeLog);
    }

    @Override
    public Response redExchangeRequest(TppTradeLog tppTradeLog) {
        return transferFromPlatform(tppTradeLog);
    }
    
    @Override
    public Response wineCouponsRequest(TppTradeLog tppTradeLog) {
    	return transferFromPlatform(tppTradeLog);
    }

    @Override
    public Response redExchangePayRequest(TppTradeLog tppTradeLog) {
        return getSuccessResponse();
    }
    
    @Override
    public Response wineCouponsPayRequest(TppTradeLog tppTradeLog) {
    	return getSuccessResponse();
    }

    @Override
    public Response fullBorrowLoadRequest(TppTradeLog tppTradeLog) {
        Response response = new FullBorrowLoanResponse();
        try {
            Borrow borrow = borrowDao.find(tppTradeLog.getBorrowId());
            // 平台收取管理费
            double manageFee = 0.0d;
            JSONObject memo = JSON.parseObject(tppTradeLog.getMemo());
            String manageFeeStr = StringUtil.isNull(memo.getString("manageFee"));
            if (StringUtil.isNotBlank(manageFeeStr)) {
                manageFee = BigDecimalUtil.round(DataUtils.toDouble(manageFeeStr), 2);
            }
            FullBorrowLoanParam parameter = new FullBorrowLoanParam();
            parameter.setOrderId(tppTradeLog.getOrderNo());
            parameter.setReqTime(tppTradeLog.getAddTime().getTime());
            String testBorrowId = borrowPrx + String.valueOf(tppTradeLog.getBorrowId());
            parameter.setBorrowId(testBorrowId); // 标ID
            parameter.setBorrowName(borrow.getName());
            parameter.setBorrowUserId(String.valueOf(borrow.getUser().getTppUserCustId()));
            parameter.setBorrowUserName(borrow.getUser().getUserName());
            parameter.setAmount(tppTradeLog.getMoney());
            parameter.setFee(manageFee); // 平台收取管理费
            response = adaptedPayService.loan(parameter);
        } catch (Exception e) {
            response.setResponseMsg("RPC 调用失败");
            response.setStatus(ResponseStatus.FAILURE);
            logger.info("BFRPCRequestServiceImpl#fullBorrowLoadRequest 调用失败 ", e);
        }
        return response;
    }

    @Override
    public Response flowBorrowRefundRequest(TppTradeLog tppTradeLog) {
        Response response = new FlowBorrowResponse();
        try {
            Borrow borrow = borrowDao.find(tppTradeLog.getBorrowId());
            FlowBorrowParam parameter = new FlowBorrowParam();
            parameter.setOrderId(tppTradeLog.getOrderNo());
            parameter.setReqTime(tppTradeLog.getAddTime().getTime());
            String testBorrowId = borrowPrx + String.valueOf(tppTradeLog.getBorrowId());
            parameter.setBorrowId(testBorrowId); // 标ID
            parameter.setBorrowName(borrow.getName());
            parameter.setBorrowUserId(String.valueOf(borrow.getUser().getTppUserCustId()));
            parameter.setBorrowUserName(borrow.getUser().getUserName());

            JSONObject memo = JSON.parseObject(tppTradeLog.getMemo());
            BorrowTender borrowTender = borrowTenderDao.getTenderByBillNo(memo.getString("tenderBilNo"));
            User borrowTenderUser = borrowTender.getUser();
            FlowBorrowParam.TenderUser tenderUser = new FlowBorrowParam.TenderUser();
            tenderUser.setUserId(String.valueOf(borrowTenderUser.getTppUserCustId()));
            tenderUser.setUserName(borrowTenderUser.getUserName());
            tenderUser.setAmount(borrowTender.getAccount());
            parameter.setTenderUsers(Arrays.asList(tenderUser));
            response = adaptedPayService.flow(parameter);
        } catch (Exception e) {
            response.setResponseMsg("RPC 调用失败");
            response.setStatus(ResponseStatus.FAILURE);
            logger.info("BFRPCRequestServiceImpl#flowBorrowRefundRequest 调用失败 ", e);
        }
        return response;
    }

    private Response getSuccessResponse() {
        Response response = new GenericResponse();
        response.setResponseMsg("提交成功");
        response.setStatus(ResponseStatus.SUCCESS);
        return response;
    }

    private Response transferFromPlatform(TppTradeLog tppTradeLog) {
        Response response = new TransferAccountsResponse();
        try {
            // 调用转账接口（平台转到用户）
            TransferAccountsParameter parameter = new TransferAccountsParameter();
            parameter.setOrderId(tppTradeLog.getOrderNo());
            parameter.setPayerUserId(tppTradeLog.getTppUserCustId());
            parameter.setPayeeUserId(tppTradeLog.getToTppUserCustId());
            parameter.setPayerType(AccountType.MERCHANT.getType());
            parameter.setPayeeType(AccountType.NORMAL.getType());
            parameter.setAmount(tppTradeLog.getMoney());
            parameter.setFee(0.00);// 平台收取管理费
            parameter.setFeeTakenOn(FeeTakenOnType.PAYER.getType());
            parameter.setReqTime(tppTradeLog.getAddTime().getTime());
            response = adaptedPayService.transferAccounts(parameter);
        } catch (Exception e) {
            response.setResponseMsg("RPC 调用失败");
            response.setStatus(ResponseStatus.FAILURE);
            logger.info("BFRPCRequestServiceImpl#redExchangeRequest 调用失败 ", e);
        }
        return response;
    }
    
    @Override
    public Response experienceRequest(TppTradeLog tppTradeLog) {
        return transferFromPlatform(tppTradeLog);
    }

}
